package juc;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class TestCopyOnWriteArrayList {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(new HelloThread()).start();
        }
    }
}

class HelloThread implements Runnable {

//    private static List<String> list = Collections.synchronizedList(new ArrayList<String>() {{
//        add("AA");
//        add("BB");
//        add("CC");
//    }});

    /**
     * CopyOnWriteArrayList
     * 注意:添加操作多时，效率低，每次添加都会复制
     * 并发迭代操作时可选
     */
    private static List<String> list = new CopyOnWriteArrayList<String>() {{
        add("AA");
        add("BB");
        add("CC");
    }};

    @Override
    public void run() {
        test1();
    }

    public void test1() {
        Iterator<String> iter = list.iterator();
        while (iter.hasNext()) {
            System.out.println(iter.next());
            list.add("XX" + (int) (Math.random() * 10));
        }
    }

    public void test2() {

    }
}
